package com.gx.security.message_digest;

import com.sun.crypto.provider.HmacMD5;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

/**
 * Created by gx on 2017/3/28.
 */
public class MACTest {
    private static final String src = "imooc security hmac";

    public static void main(String[] args) {
        jdkHmacMD5();
        bcHmacMD5();
    }


    public static void jdkHmacMD5() {
        try {
            //初始化KeyGenerator
            KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
            //产生秘钥
            SecretKey secretKey = keyGenerator.generateKey();
            //获得秘钥
            byte[] key = secretKey.getEncoded();
            //这一步初始化KEY 指定
//            不指定 随机生成 kry和BC实现 有所区别        两次执行不一样
            key = Hex.decodeHex(new char[]{'a','a','a','a','a','a','a','a','a','a'});
//            还原秘钥
            SecretKey resroreSecretKey = new SecretKeySpec(key, "HmacMD5");
            //实例化MAC
            Mac mac = Mac.getInstance(resroreSecretKey.getAlgorithm());
            //初始化MAC
            mac.init(resroreSecretKey);
            //获得结果
            byte[] result = mac.doFinal(src.getBytes());
            System.out.println("jdk hmacMd5:" + Hex.encodeHexString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void bcHmacMD5() {
        try {
            //实例 hmac
            HMac hMac =  new HMac(new MD5Digest());
            //初始化 hmac
            hMac.init(new KeyParameter(org.bouncycastle.util.encoders.Hex.decode("aaaaaaaaaa")));
            hMac.update(src.getBytes(),0,src.getBytes().length);
            //产生输出
            byte [] hmacMD5Bytes = new byte[hMac.getMacSize()];
            hMac.doFinal(hmacMD5Bytes,0);
            System.out.println("bc hmacMd5:" + org.bouncycastle.util.encoders.Hex.toHexString(hmacMD5Bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

